package com.zfzs.post.ali;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;
import java.io.File;
import java.io.InputStream;

/**
 * 阿里云上传工具类
 *
 * @author wq
 */
public class AliOssUtils {

    private static final String endpoint = "oss-cn-hangzhou.aliyuncs.com";

    private static final String accessKeyId = "LTAInTZVEFiyk6sS";

    private static final String accessKeySecret = "7fjctqfznnmRn6evvP2fUeBBzS9crE";

    private static final String bucketName = "zfzs-img";

    public static final String IMG_URL = "https://zfzs-img.oss-cn-hangzhou.aliyuncs.com/";

    public static InputStream downLoad(String objectName) {
        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖，不存在则新建。
        OSSObject object = ossClient.getObject(bucketName, objectName);
        InputStream inputStream = object.getObjectContent();

        // 关闭OSSClient。
        ossClient.shutdown();
        return inputStream;
    }

    public static void downloadToFile(String objectName, String downloadUrl) {
        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖，不存在则新建。
        ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(downloadUrl));

        // 关闭OSSClient。
        ossClient.shutdown();

    }


    public static void deleteFile(String objectName) {
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        ossClient.deleteObject(bucketName, objectName);
        ossClient.shutdown();

    }


    public static String uploadBytes(InputStream inputStream, String objectName) {
        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        // 上传Byte数组。
        ossClient.putObject(bucketName, objectName, inputStream);

        // 关闭OSSClient。
        ossClient.shutdown();
        return IMG_URL + objectName;
    }


    public static void uploadByPath(String filePath, String objectName) {
        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        PutObjectResult objectResult = ossClient.putObject(bucketName, objectName, new File(filePath));

        ossClient.shutdown();
    }
}
